// @ts-ignore
import crypto from 'crypto-js'
import { Base64 } from 'js-base64'

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}
function formatYMR_cn(dateStr: string) {
  // 将日期格式化成ios可以识别的格式
  dateStr = dateStr.replace(/-/g, '/')
  let date = new Date(dateStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1)
  const day = String(date.getDate())
  const formattedDate = `${year}年${month}月${day}日`
  return formattedDate
}

function formatDate_dot(dateStr: string) {
  // 将日期格式化成ios可以识别的格式
  dateStr = dateStr.replace(/-/g, '/')
  let date = new Date(dateStr)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('.')
}

function openSettingModal(
  title: string,
  content: string,
  confirmText: string
): void {
  wx.showModal({
    title: title,
    content: content,
    showCancel: false,
    confirmText: confirmText,
    success() {
      wx.openSetting({
        success(res) {
          console.log('openting authSetting:', res.authSetting)
        },
        fail: (error) => {
          console.log('error:', error)
        }
      })
    }
  })
}

function getAuthSetting(
  scope: string,
  successCallback: () => void,
  failCallback: () => void
) {
  wx.getSetting({
    success(res: any) {
      console.log('res.authSetting:', res.authSetting)
      // alert('getAuthSetting:'+scope+'|||'+ (Object.keys(res.authSetting).join(','))+'|||'+Object.values(res.authSetting).join(','))
      if (res.authSetting[scope]) {
        // 开始录音
        successCallback()
      } else {
        // 没有授权,就授权
        wx.authorize({
          scope: scope,
          success() {
            successCallback()
          },
          fail() {
            failCallback()
          }
        })
      }
    },
    fail(error) {
      console.error('getAuthSetting error:', error)
      // alert('getAuthSetting:'+ JSON.stringify(error))
      failCallback()
    }
  })
}

function isLogin(): boolean {
  return !!wx.getStorageSync('token')
}

function createRecorderManager() {
  return wx.getRecorderManager()
}

function randomFileName(ext: string = ''): string {
  const randomString =
    Date.now().toString(36) + Math.random().toString(36).substring(2)
  return randomString + ext
}

function formatSeconds(seconds: number) {
  seconds = Math.floor(seconds)
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${String(minutes).padStart(2, '0')}:${String(
    remainingSeconds
  ).padStart(2, '0')}`
}

function maskPhoneNumber(phoneNumber: string) {
  if (phoneNumber) {
    return phoneNumber.slice(0, 3) + '****' + phoneNumber.slice(7)
  } else {
    return ''
  }
}
function alert(content: string) {
  wx.showModal({
    title: '',
    content: content,
    showCancel: false
  })
}

function throttle(func: Function, delay: number) {
  let timer = null as any
  return function () {
    if (!timer) {
      func.apply(this, arguments)
      timer = setTimeout(() => {
        timer = null
      }, delay)
    }
  }
}
function randomStr(length = 4) {
  let result = ''
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  const charactersLength = characters.length
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength))
  }
  return result
}

function computeSignature(accessKeySecret: string, canonicalString: string) {
  return crypto.enc.Base64.stringify(
    crypto.HmacSHA1(canonicalString, accessKeySecret)
  )
}
function getAliSTS(credentials: any) {
  const date = new Date()
  date.setHours(date.getHours() + 1)
  const policyText = {
    expiration: date.toISOString(), // 设置policy过期时间。
    conditions: [
      // 限制上传大小。
      ['content-length-range', 0, 1024 * 1024 * 1024]
    ]
  }
  const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
  const signature = computeSignature(credentials.accessKeySecret, policy)
  const formData = {
    OSSAccessKeyId: credentials.accessKeyId,
    signature,
    policy,
    'x-oss-security-token': credentials.securityToken
  }
  return formData
}

const markReg = /[,，.。、;；?？'"‘’“”!！\da-zA-Z]/g

function getStatusBarAndMenuButtonInfo() {
  // 单位都是px
  // 胶囊高度
  let menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  let menuButtonHeight = menuButtonInfo.height //  获取胶囊高度
  let winInfo = wx.getWindowInfo()
  // 状态栏高度
  let statusBarHeight = winInfo.statusBarHeight
  // 胶囊距离状态栏边距
  let menuButtonGutter = menuButtonInfo.top - statusBarHeight //  获取top值
  // 导航栏高度：胶囊按钮+上下边距
  let menuBarHeight = menuButtonHeight + menuButtonGutter * 2
  return { menuButtonHeight, statusBarHeight, menuButtonGutter, menuBarHeight }
}

// 将文本每N个字分成一行
function splitContentByWordNums(content: string, rowWordNum: number) {
  let result = ''
  let rowList = []
  for (let i = 0; i < content.length; i++) {
    if (i % rowWordNum === 0 && i !== 0) {
      rowList.push(result)
      result = ''
    }
    result += content[i]
  }
  if (result) {
    rowList.push(result)
  }
  return rowList
}

// 分页配置项
let splitContentPageOptions = {
  riji_rowWordNum: 8, // 日记 每行显示字数
  riji_firstPageRowNum: 10, // 日记第一页显示行数
  riji_otherPageRowNum: 12, // 日记其他页显示行数
  shuxin_rowWordNum: 8, // 书写 每行显示字数
  shuxin_firstPageRowNum: 8, // 书写第一页显示行数
  shuxin_otherPageRowNum: 9, // 书写其他页显示行数
  shige_rowWordNum: 8, // 诗歌 每行显示字数
  shige_firstPageRowNum: 7, // 诗歌第一页显示行数
  shige_otherPageRowNum: 7, // 诗歌其他页显示行数
  spring_rowWordNum:8,
  spring_firstPageRowNum: 13, // 春节祝福语第一页显示行数
  spring_otherPageRowNum: 13 // 春节祝福语其他页显示行数
}
function splitContentForPage(item: any, options: any) {
  let pageOptions = Object.assign({}, splitContentPageOptions, options)
  // 先分行，再分页，第一页统一显示为2行
  let content = item.content || ''
  if (!content) {
    return []
  }
  // 模板类型
  
  let templateCode = item.templateCode
  let rowWordNum = 8
  let firstPageRowNum = 2
  let otherPageRowNum = 10
  // 春节祝福
  // console.log('item:', item)
  // console.log('typeof item:', typeof item.cjFlag)
  if(item.cjFlag == 1){
    rowWordNum = 8
    firstPageRowNum = options.firstPageRowNum || 12
    otherPageRowNum = options.otherPageRowNum || 12
  }else {
    if (templateCode === 'riji') {
      rowWordNum = pageOptions.riji_rowWordNum
      firstPageRowNum = pageOptions.riji_firstPageRowNum
      otherPageRowNum = pageOptions.riji_otherPageRowNum
    } else if (templateCode === 'shuxin') {
      rowWordNum = pageOptions.shuxin_rowWordNum
      firstPageRowNum = pageOptions.shuxin_firstPageRowNum
      otherPageRowNum = pageOptions.shuxin_otherPageRowNum
    } else if (templateCode === 'shige') {
      rowWordNum = pageOptions.shige_rowWordNum
      firstPageRowNum = pageOptions.shige_firstPageRowNum
      otherPageRowNum = pageOptions.shige_otherPageRowNum
    } else if (templateCode === 'spring'){
      rowWordNum = pageOptions.spring_rowWordNum
      firstPageRowNum = pageOptions.spring_firstPageRowNum
      otherPageRowNum = pageOptions.spring_otherPageRowNum
    }
  }
  
  


  let rowList = [] as any[]
  if (templateCode === 'riji' || templateCode === 'shuxin' || templateCode === 'spring') {
    // 删除文本中的所有空格
    content = content.replace(/\s+/g, '')
    // 先分行，再分页

    for (let i = 0; i < content.length; ) {
      let rowContent = ''
      for (let wNum = 0; wNum < rowWordNum && i < content.length; ) {
        let char = content[i]
        // console.log('char:', char)
        // 标点符号或者数字或者字母
        if (char.match(markReg)) {
          // 日记的符号比较宽
          // if (templateCode === 'riji') {
          //   wNum += 0.5
          // } else {
          //   wNum += 0.25
          // }
          wNum += 0.5
        } else {
          wNum += 1
        }
        rowContent += char
        i += 1
      }
      let nextChar = content[i] || ''
      // 如果下一行是标点符号，那就再截取1个
      if (/[,，.。、;；?？'"‘’“”!！]/.test(nextChar)) {
        rowContent += nextChar
        i++
      }

      // 如果是日记，一行一个标点符号都没有，则可以再加1个字
      // if (templateCode === 'shuxin' && !rowContent.match(markReg)) {
      //   rowContent += content[i] || ''
      //   i++
      // }

      rowList.push(rowContent)
    }
  } else {
    // 诗歌
    let tempRowList = content.split('\n')
    let newRowList = [] as any[]
    for (let i = 0; i < tempRowList.length; i++) {
      let rowContent = tempRowList[i]
      
      if (rowContent.length > rowWordNum) {
        newRowList = newRowList.concat(splitContentByWordNums(rowContent, rowWordNum))
      }else {
        newRowList.push(rowContent)
      }
    }
    rowList = newRowList
  }

  // 将行按页划分，第一页2行，其他页10行
  let pageList = [] as any[]
  for (let i = 0; i < rowList.length; ) {
    let page = [] as any[]
    if (i === 0) {
      page = rowList.slice(i, i + firstPageRowNum)
      i += firstPageRowNum
    } else {
      page = rowList.slice(i, i + otherPageRowNum)
      i += otherPageRowNum
    }
    pageList.push(page)
  }
  // console.log('pageList:',pageList)
  return pageList
}
function getAudioUrl(audioUrl: string) {
  return new Promise((resolve) => {
    const deviceInfo = wx.getDeviceInfo()
    let isIos = deviceInfo.system.toLowerCase().includes('ios')
    if (isIos) {
      resolve(audioUrl)
    } else {
      // 安卓的话，需要先把文件下载下来才能播放
      wx.downloadFile({
        url: audioUrl,
        success: (res) => {
          // console.log('download res:',res)
          // console.log('that.data._audioContext2:',that.data._audioContext)
          if (res.statusCode === 200) {
            resolve(res.tempFilePath)
          }
        },
        fail: (err) => {
          console.log('download err:', err)
          resolve(audioUrl)
        }
      })
    }
  })
}

module.exports = {
  formatTime,
  formatDate_dot,
  openSettingModal,
  getAuthSetting,
  isLogin,
  createRecorderManager,
  randomFileName,
  formatSeconds,
  maskPhoneNumber,
  alert,
  formatYMR_cn,
  throttle,
  randomStr,
  getAliSTS,
  markReg,
  getStatusBarAndMenuButtonInfo,
  splitContentForPage,
  getAudioUrl
}
